<template>

    <section class="main">
        <div class="container">
            <div class="crumbs">
                <el-breadcrumb separator="/">
                    <!--                TODO-->
                    <el-breadcrumb-item><i class="el-icon-lx-home"></i> 首页</el-breadcrumb-item>
                    <el-breadcrumb-item><i class="el-icon-office-building"></i>部门管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div id="add">
                <el-button-group>
                    <!--                TODO-->
                    <el-button @click="addDep($event)" class="el-icon-circle-plus-outline">添加部门</el-button>
                    <el-button @click="modDep($event)" class="el-icon-edit">修改部门</el-button>
                    <el-button @click="delWarning()" class="el-icon-remove-outline" style="margin-right: 0"
                               type="danger">删除部门
                    </el-button>
                </el-button-group>

                <div>
                    <hr style="margin-top: 5px;margin-bottom: 5px;">
                </div>


            </div>

            <div id="app" v-cloak>
                <!--                v-cloak防止网络加载慢的时候出现源代码暴露-->
                <el-button-group>
                    <el-button :key="dep.depId" @click="findDepDetail($event,dep)" type="primary" v-for="dep in deps">
                        {{dep.depName}}
                    </el-button>
                </el-button-group>
                <div>
                    <hr style="margin-top: 5px;margin-bottom: 5px;">
                </div>
                <div class="dep-content">
                    <div id="dev-id"></div>
                    <div id="user_id"></div>
                    <div id="dep-name"></div>
                    <div id="head-count"></div>

                </div>
                <!--                部门基本数据区域-->
                <div class="box" v-show="depSelected">
                    <div class="top">
                        <span class="basic-data">部门：</span>
                        <el-tag>{{depForm.depName}}</el-tag>
                        <span class="basic-data basic-data-right">人数：</span>
                        <el-tag>{{depForm.headCount}}</el-tag>

                    </div>
                </div>
                <!--                表格部分-->
                <div style="height: 10px;width: 100%;"></div>
                <!--                分页显示功能-->
                <el-table :data="(currentDepStaffs||[])" style="width: 100%">
                    <!--                <el-table :data="depForm.staffs.slice(Number((currentPage-1)*pagesize),Number(currentPage*pagesize))" style="width: 100%">-->
                    <el-table-column type="expand">
                        <template slot-scope="items">
                            <el-form class="demo-table-expand" inline label-position="left">
                                <el-form-item label="姓名:">
                                    <span v-if="currentDepStaffs!=[]">{{items.row.staffName }} <span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="工号:">
                                    <span>{{items.row.id}}<span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="身份证号:">
                                    <span>{{items.row.idCard}}<span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="手机号:">
                                    <span>{{items.row.tel}}<span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="职级:">
                                    <span>{{items.row.roleName}}<span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="工资:">
                                    <span>{{items.row.wages}}<span style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="入职时间">
                                    <span>{{items.row.joinDate}}<span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="离职时间:">
                                    <span>{{items.row.dismissionDate}}<span
                                            style="margin-left: 10px;margin-right: 5px;">|</span></span>
                                </el-form-item>
                                <el-form-item label="地址:">
                                    <span>{{items.row.addr}}</span>
                                </el-form-item>

                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="姓名"
                            prop="staffName">
                    </el-table-column>
                    <el-table-column
                            label="工号"
                            prop="id">
                    </el-table-column>
                    <el-table-column
                            label="状态"
                            prop="status">
                    </el-table-column>
                    <el-table-column
                            label="工资"
                            prop="wages">
                    </el-table-column>
                </el-table>
                <!--分页-->
                <el-pagination
                        :page-size="pagesize"
                        :total="dataCount"
                        @current-change="currentChange"
                        background
                        layout="prev, pager, next"
                        v-model:current-page="currentPage">
                </el-pagination>


            </div>
        </div>
        <div id="addDep-msgBox">
            <el-dialog
                    :title="processDepTitle"
                    :visible.sync="dialogVisible"
                    width="30%"
            >
                <!--                :before-close="handleClose"-->
                <!--***************************表单内容*****************************************-->
                <el-form :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="100px" ref="ruleForm">
                    <el-form-item label="部门名称" prop="newDepName">
                        <el-input v-model="ruleForm.newDepName"></el-input>
                    </el-form-item>
                    <el-form-item label="部门编号" prop="newDepId">
                        <el-input v-model="ruleForm.newDepId"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="submitForm('ruleForm')" type="primary">立即创建</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>

                    </el-form-item>

                    <!--***************************************************************************-->
                    <!--                    <span slot="footer" class="dialog-footer">-->
                    <!--                        <el-button @click="dialogVisible = false">取 消</el-button>-->
                    <!--                        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
                    <!--                        <el-button type="primary" @click="resetForm('ruleForm')">确 定</el-button>-->
                    <!--                    </span>-->
                </el-form>
            </el-dialog>
        </div>
    </section>
</template>

<script>
    // import axios from "axios";
    import { Vue } from 'vue-i18n';

    export default {
        name: 'app',
        data() {
            return {
                // 部门数组
                deps: [],
                // 某个部门的成员等数据
                depForm: {
                    depId: '',
                    depName: '',
                    headCount: -1,
                    staffs: [{
                        addr: '',
                        dismissionDate: '',
                        id: '',
                        idCard: '',
                        jobNumber: '',
                        joinDate: '',
                        password: '',
                        phone: '',
                        roleId: '',
                        roleName: '',
                        staffName: '',
                        status: '',
                        tel: '',
                        url: '',
                        wages: ''
                    }]
                },
                // 当前页
                currentPage: 1,
                // 每页数据条数
                pagesize: 3,
                // 数据总条数
                dataCount: 0,
                // 总页数
                pageCount: 0,
                // 用来判断是否要显示部门详情
                depSelected: false,
                // 装部门的员工数据
                currentDepStaffs: null,
                // 当前选择的部门的主键
                currentDepPrimaryKey: -1,
                // 当前显示详情的部门id
                currentDepId: null,
                // 当前选择的部门名称
                currentDepName: null,
                // depId:-1
                // 用于决定是否显示弹出层的内容
                dialogVisible: false,
                // 对部门的操作类型：新增|修改
                processDepTitle: null,
                // 表单数据
                ruleForm: {
                    newDepName: '',
                    newDepId: ''
                },
                rules: {
                    newDepName: [
                        { required: true, message: '部门名称不能为空哦！', trigger: 'blur' },
                        { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                    ],
                    newDepId: [
                        { required: true, message: '部门名称不能为空哦！', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ]
                }

            };
        },
        // 页面加载后就近数据库查询
        created: function() {
            const _this = this;
            _this.$axios.get('dep/getDep', {})
                .then(function(response) {
                    // console.log('拿到数据了：' + response);
                    // 数据赋值给deps
                    _this.deps = response.data;

                })
                .catch(function(error) {
                    console.log('出错了：' + error);
                });
        },
        // TODO 部门被选中了应该更改样式
        methods: {
            // 查询部门信息，并进行分页
            findDepDetail(event, dep) {
                // 被选中时更改样式
                // console.log(event.target.classList.value);
                // event.target.classList.value="el-button el-button--success el-button--small";
                // event.target.type="primary";
                // console.log(val.depId);
                const _this = this;
                this.$axios.get('dep/getDetail?depId=' + dep.depId, {})
                    .then(function(response) {
                        /**
                         * 当部门下的员工为空时，将组件中需要用到的数据进行声明为空，防止出现undefined
                         * 当部门下的员工不为空时直接接受赋值
                         * @type {string}
                         */
                        _this.depForm.depId = response.data.depId;
                        _this.depForm.depName = response.data.depName;
                        _this.depForm.headCount = response.data.headCount;
                        // alert(_this.depForm.headCount);
                        if (response.data.staffs.length != 0) {
                            _this.depForm.staffs = response.data.staffs;
                            console.log('标记' + _this.depForm.staffs);
                        } else {
                            _this.depForm.staffs = [{
                                addr: '',
                                dismissionDate: '',
                                id: '',
                                idCard: '',
                                jobNumber: '',
                                joinDate: '',
                                password: '',
                                phone: '',
                                roleId: '',
                                roleName: '',
                                staffName: '',
                                status: '',
                                tel: '',
                                url: '',
                                wages: ''
                            }];
                        }
                        // 具体部门的数据赋值
                        _this.dataCount = response.data.staffs.length;
                        // 存储当前部门的名字
                        _this.currentDepName = dep.depName;
                        // console.log("类型为："+ _this.depForm);
                        // 当前选择的部门id赋值
                        _this.currentDepId = dep.depId;
                        _this.currentDepPrimaryKey = dep.id;
                        // 显示当前部门的详情页
                        _this.depSelected = true;
                        // 改变当前页数据
                        _this.currentDepStaffsChange();
                    }).catch(function(erro) {
                    console.log('出错了：' + erro);
                });
            },
            addDep(event) {
                let _this = this;
                _this.ruleForm.newDepName = '';
                _this.ruleForm.newDepId = '';
                _this.processDepTitle = '新增部门';
                // alert('This function is under completing, show your patience please!');
                _this.dialogVisible = true;
            },
            // 修改部门
            modDep() {
                let _this = this;
                _this.ruleForm.newDepName = _this.currentDepName;
                _this.ruleForm.newDepId = _this.currentDepId;
                _this.processDepTitle = '修改部门';
                // alert('This function is under completing, show your patience please!');
                _this.dialogVisible = true;
            },
            // 执行增加部门的弹出层关不函数
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();

                    })
                    .catch(_ => {
                    });
            },
            delDep() {
                const _this = this;
                // 解决post方法发送数据后台娶不到
                let param = new URLSearchParams();
                param.append('depId', this.currentDepId);
                // console.log("需要删除的depId："+this.currentDepId);
                if (this.currentDepId == -1) {
                    _this.openVn('未选择部门');
                    return;
                }
                this.$axios.post('/dep/delDep', param, {}).then(function(response) {
                    // console.log(_this.depForm);
                    // 后台数据删除后，将前端的数据也进行更新
                    // 当前删除的部门的depId
                    let tmp = -1;
                    // console.log('a'=='a');
                    for (let i = 0; i < _this.deps.length; i++) {
                        // console.log("前端更新了吗");
                        // console.log("_this.currentDepId:"+_this.currentDepId);
                        if (_this.currentDepId == _this.deps[i].depId) {
                            tmp = i;
                            _this.deps.splice(tmp, 1);
                        }
                    }

                    _this.openVn('部门删除成功');
                    _this.depSelected = false;
                    _this.depForm.staffs = null;
                }).catch(function(erro) {
                    console.log(erro);
                });
            },
            // 页面操作提示
            openVn(msg) {
                const h = this.$createElement;
                this.$message({
                    message: h('p', null, [
                        h('span', null, msg),
                        h('i', { style: 'color: green' }, '')
                    ])
                });
            },
            // 执行删除钱的警告
            delWarning() {
                let _this = this;
                this.$confirm('您正在进行部门【' + _this.currentDepName + '】删除操作, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // console.log("需要删除的depId："+this.currentDepId);
                    this.delDep();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 表单提交与重置
            submitForm(formName) {//formName=ruleForm
                // alert(formName);
                let _this = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let _this = this;
                        let param = new URLSearchParams();
                        param.append('newDepName', _this.ruleForm.newDepName);
                        param.append('newDepId', _this.ruleForm.newDepId);
                        if (_this.processDepTitle == '新增部门') {
                            // console.log("param:"+param);
                            // post方法需要包装数据
                            // 执行部门创建的提交
                            // 当提交的数据在数据库中已经存在，已在数据库设置唯一键，重复的部门名称和或部门id将无法添加
                            for (let i = 0; i < _this.deps.length; i++) {
                                if (_this.ruleForm.newDepName == _this.deps[i].depName || this.ruleForm.newDepId == _this.deps[i].depId) {
                                    _this.openVn('当前部门名称或部门id已经存在，请直接使用或是添加其他部门吧(*^__^*)');
                                    return;
                                }
                            }
                            this.$axios.post('/dep/addDep', param, {}).then(function(response) {
                                // 发送成功后
                                // 将前端的部门表进行更新
                                _this.openVn('部门添加成功(*^__^*)');
                                // console.log(response.data);
                                _this.deps.push(response.data);
                                // console.log(_this.deps);
                                _this.dialogVisible = false;
                                // console.log("deps数据已更新："+_this.deps[4]);
                            }).catch(function(erro) {
                                console.log('出现错误了：' + erro);
                            });
                        } else {
                            // 当提交的数据在数据库中已经存在，已在数据库设置唯一键，重复的部门名称和或部门id将无法添加
                            for (let i = 0; i < _this.deps.length; i++) {
                                if (_this.ruleForm.newDepName == _this.deps[i].depName && this.ruleForm.newDepId == _this.deps[i].depId) {
                                    _this.openVn('未做修改');
                                    return;
                                }
                            }
                            param.append('id', _this.currentDepPrimaryKey);
                            // 执行修改部门操作
                            this.$axios.post('/dep/modDep', param, {}).then(function(response) {
                                // 发送成功后
                                // 将前端的部门表进行更新
                                _this.openVn('部门修改成功(*^__^*)');
                                // console.log(response.data);
                                // TODO
                                _this.deps=response.data;
                                // console.log(_this.deps);
                                _this.dialogVisible = false;
                                // console.log("deps数据已更新："+_this.deps[4]);
                            }).catch(function(erro) {
                                console.log('出现错误了：' + erro);
                            });
                        }

                    } else {
                        // 数据的合法性已经在表单中做好了，空数据无法提交
                        console.log('数据不合法!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 改变当前页的数据，每次更换当前页调用一次
            currentDepStaffsChange() {
                let _this = this;
                _this.currentDepStaffs = _this.depForm.staffs.slice(Number((_this.currentPage - 1) * _this.pagesize), Number(_this.currentPage * _this.pagesize));
                console.log('标记1：' + _this.currentDepStaffs);
            },
            // 上一页下一页点击事件
            currentChange(currentPage) {
                let _this = this;
                // console.log("currentPage:"+currentPage);
                _this.currentPage = currentPage;
                // console.log("_this.currentPage:"+_this. currentPage);
                _this.currentDepStaffsChange();
            }
        }
    };

</script>

<style scoped>
    a {
        text-decoration: none;
        color: white;
    }

    .container {
        position: relative;
    }

    .basic-data {
        font-size: 14px;
        color: rgba(43, 43, 43, 0.9);
    }

    .basic-data-right {
        margin-left: 30px;
    }
</style>
